#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <cstring>
#include <arpa/inet.h>
#include "log.hpp"

extern Log lg;

enum
{
    SOCKET_ERR = 1,
    BIND_ERR,
    LISTEN_ERR
};

class Sock
{
public:
    Sock()
    {
    }
    ~Sock()
    {
    }

public:
    // 创建套接字
    void Socket()
    {
        sockfd_ = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd_ < 0)
        {
            //  lg(Fatal, "socket error,errno:%d,errstring:%s", errno, strerror(errno));
            std::cout<<"socket error."<<std::endl;
            exit(SOCKET_ERR);
        }
    }
    // 绑定--需要端口
    void Bind(uint16_t sockport)
    {
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(sockport);
        local.sin_addr.s_addr = INADDR_ANY;
        if (bind(sockfd_, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            lg(Fatal, "bind error,errno:%d,errstring:%s", errno, strerror(errno));
            exit(BIND_ERR);
        }
    }

    // 监听
    int backlog = 5;
    void Listen()
    {
        if (listen(sockfd_, backlog) < 0)
        {
            lg(Fatal, "listen error,errno:%d,errstring:%s", errno, strerror(errno));
            exit(LISTEN_ERR);
        }
    }
    // 连接,接收---需要接收到ip地址和端口号--传出去--需要返回新的newfd
    int Accept(std::string *clientip, uint16_t *clientport)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int newfd = accept(sockfd_, (struct sockaddr *)&peer, &len);
        if (newfd < 0)
        {
            lg(Warning, "accept aerror,errno:%d,errstring:%s", errno, strerror(errno));
        }
        char in_ipstr[64];
        // 网络转字符串
        inet_ntop(AF_INET, &peer.sin_addr, in_ipstr, sizeof(in_ipstr));
        *clientip = in_ipstr;
        *clientport = ntohs(peer.sin_port);
        return newfd;
    }

    bool Connect(const std::string& ip,const uint16_t &port)
    {
        struct sockaddr_in peer;
        memset(&peer,0,sizeof(peer));
        peer.sin_family=AF_INET;
        // 主机转网络
        peer.sin_port=htons(port);
        inet_pton(AF_INET,ip.c_str(),&(peer.sin_addr));
        int n=connect(sockfd_,(struct sockaddr*)&peer,sizeof(peer));
        if(n<0)
        {
            std::cerr<<"connect error: "<<ip<<": error"<<std::endl;
            return false;
        }
        return true;

    }
    int Fd()
    {
        return sockfd_;
    }
    void Closefd()
    {
        close(sockfd_);
    }

private:
    int sockfd_;
};